package com.ruoyi.web.agora;


import com.ruoyi.framework.config.properties.AgoraProperties;
import com.ruoyi.web.agora.media.RtcTokenBuilder;
import com.ruoyi.web.agora.media.RtcTokenBuilder.Role;
import com.ruoyi.web.agora.rtm.RtmTokenBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

;

/**
 * 创建声网直播和聊天TOKEN
 */
@Component
public class AgoraToken {

    @Autowired
    private AgoraProperties agoraProperties;
    static RtcTokenBuilder token = new RtcTokenBuilder();


    /**
     * 根据唯一用户ID创建声网直播TOKEN
     *
     * @param uid 用户ID
     * @return
     */
    public String buildTokenWithUid(String name, Integer uid) {
        return token.buildTokenWithUid(agoraProperties.getAppId(), agoraProperties.getAppCertificate(),
            name, uid, Role.Role_Publisher, createTimestamp());
    }

    /**
     * 根据唯一用户ID创建声网直播TOKEN
     *
     * @return
     */
    public String buildTokenWithUserToken(String channelName, Integer uid) {
        return token.buildTokenWithUid(agoraProperties.getAppId(), agoraProperties.getAppCertificate(),
            channelName, uid, Role.Role_Publisher, createTimestamp());
    }

    /**
     * 根据用户ID创建云信聊天TOKEN
     *
     * @param uid
     * @return
     * @throws Exception
     */
    public String rtmTokenBuilder(String uid) throws Exception {
        RtmTokenBuilder token = new RtmTokenBuilder();
        String result = token.buildToken(agoraProperties.getAppId(), agoraProperties.getAppCertificate(), String.valueOf(uid), RtmTokenBuilder.Role.Rtm_User, 0);
        return result;
    }

    private int createTimestamp() {
        return (int) (System.currentTimeMillis() / 1000 + agoraProperties.getExpirationTimeInSeconds());
    }
}
